package com.heima.comment.service.Impl;

import com.heima.comment.pojos.ApComment;
import com.heima.comment.service.CommentHotService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CommentHotServiceImpl implements CommentHotService {


    @Autowired
    MongoTemplate mongoTemplate;
    /**
     * 处理热点评论
     *
     * @param entryId
     * @param apComment
     */
    @Override
    @Async
    public void hotCommentExecutor(Long entryId, ApComment apComment) {
        //查询当前文章所有热点评论,并按照点赞数倒序
        List<ApComment> apHotComments = mongoTemplate.find(Query.query(Criteria.where("entryId").is(entryId)
                .and("type").is(0).and("flag").is(1)
        ).with(Sort.by(Sort.Direction.DESC, "likes")), ApComment.class);
        //判断,如果没有热点评论,新增热点评论
        if (apHotComments == null || apHotComments.size() < 5) {
            apComment.setFlag((short) 1);
            mongoTemplate.save(apComment);
            return;
        }
        //点赞数最小的热点评论
        ApComment hotComment = apHotComments.get(apHotComments.size() - 1);
        //如果当前评论数据大于5条,替换热点评论中的最后一条数据
        if (apComment.getLikes().intValue()>hotComment.getLikes().intValue()){
            if (apHotComments.size()>=5){
                hotComment.setFlag((short) 0);
                mongoTemplate.save(hotComment);
                apComment.setFlag((short) 1);
                mongoTemplate.save(apComment);
            }
        }
    }
}
